package cmd

import (
	"database/sql"
	"fmt"
	"github.com/spf13/cobra"
	"log"
	_ "github.com/go-sql-driver/mysql"
)

var user string
var dbname string

var mysqlCmd = &cobra.Command{
	Use:   "mysql",
	Short: "mysql check tool",
	Long: `mysql check'`,
	Run: func(cmd *cobra.Command, args []string)  {
		// Do Stuff Here
		log.Println("mysql command run")
		runMysqlCommand(user,password,addr,dbname)
	},
}
func init() {
	mysqlCmd.Flags().StringVarP(&user, "user", "u", "", "mysql user")
	mysqlCmd.Flags().StringVarP(&password, "password", "p", "", "mysql password")
	mysqlCmd.Flags().StringVarP(&addr, "addr", "a", "", "mysql ip address")
	mysqlCmd.Flags().StringVarP(&dbname, "dbname", "d", "", "mysql database name")


	rootCmd.AddCommand(mysqlCmd)
}
func runMysqlCommand(user string,password string,addr string,dbname string) {
	driverUrl := fmt.Sprintf("%s:%s@tcp(%s)/%s", user,password,addr,dbname)
	log.Println("driverUrl:",driverUrl)
	db, err := sql.Open("mysql", driverUrl)
	if err != nil {
		panic(err)
	}
	defer db.Close()
	err = db.Ping()
	if err != nil {
		panic(err.Error()) // proper error handling instead of panic in your app
	}
	log.Println("ok")

}
